// pages/SavePost/SavePost.js
var util = require('../../utils/util.js')
var app = getApp()
var rootUrl = app.globalData.rootDocment
var imgPublicUrl = rootUrl + 'Public/Home/images/'
var valNum = 0 
Page({ 

  /**
   * 页面的初始数据
   */
  data: {
    qdisplay:true,
    savePostAddressButton:true,
    savePostAddressMain:false,
	  cabinetID: 0,	//智能柜ID
	  cabinetNumber: 0,	//传参（智能柜编号）
	  cabinetDoorID: 0,	//柜门ID
	  cabinetDoor: 0,	//获取参数（智能柜可以使用柜门编号）
	  receivadrtp: true,	//	是否默认开启请求收货地址
	  receivadrID: null,	//	收货地址ID
	  receivname:null,	//	收货人姓名
	  receivphone:null,	//	收货人电话
	  receivaddress:null,	//	收货详细地址
    postNumber: 1,	//默认初始袋数
	  couponid: null,	//优惠券id
	  couponamount: 0,	//优惠金额
	  couponstatus:false, //优惠券是否显示
    unitprice: 0,  //单价
	  aggregateamount: 0,  //累计金额
	  totalamount: 0,  //订单总金额
	  remarks:"", //订单备注
    submitst: true, //提交状态
    submitcs: 0, //提交次数
	  imageArr: {
		  addressIcon: imgPublicUrl + 'addressIcon.png',
		  SavePostHeaderImg: imgPublicUrl + 'SavePostHeaderImg.jpg',
		  minusIcon: imgPublicUrl + 'minusIcon.png',
		  addIcon: imgPublicUrl + 'addIcon.png',
		  rightIcon: imgPublicUrl + 'rightIcon.png',
      PostBgImg: imgPublicUrl + 'PostBgImg.jpg'
	  }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.result){
      if (options.result.indexOf(rootUrl) >= 0) {  //判断是否规范
        var scoderes = options.result.replace(rootUrl, '')
        var strlenth = scoderes.replace(/[^0-9]/ig, "").length
        var strvals = parseInt(scoderes.replace(/[^0-9]/ig, ""))
        if (strlenth == 10) {
          this.setData({ cabinetNumber: strvals })
        }
      }
    }
    if (app.globalData.unitprice){
      this.setData({ unitprice: app.globalData.unitprice })
    }else{
      wx.navigateBack()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
	  app.publicchangenavigate()
		var that = this

    if (that.data.cabinetNumber){
      //请求柜子可以使用的柜门
      util.AJAX('Home/Index/getcanusecd', { cabinetnum: that.data.cabinetNumber }, function (res) { //方法体
        if (res.data.StatusCode == 100) {  //成功
          that.setData({
            qdisplay: false,
            cabinetID: res.data.Info.cid,
            cabinetDoorID: res.data.Info.id,
            cabinetDoor: res.data.Info.doornum
          })
        } else {
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: '抱歉！没有空闲的柜子了',
            success: function (res) {
              if (res.confirm) {
                wx.navigateBack()
              }
            }
          })
        }
      }, 'POST')
    }else{
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '请扫描正确的二维码',
        success: function (res) {
          if (res.confirm) {
            wx.navigateBack()
          }
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
	  var that = this
	  if (that.data.receivadrtp){
		  //判断用户是否有默认收货地址
		  util.AJAX('Home/Index/checkreceivadr', { userinfoid: app.globalData.userInfoId, userphone: app.globalData.userPhone }, function (res) { //方法体
			  if (res.data.StatusCode == 100) {  //成功
				  that.setData({
					  savePostAddressButton: false,
					  savePostAddressMain: true,
					  receivadrID: res.data.Info.id,
					  receivname: res.data.Info.name,	//	收货人姓名
					  receivphone: res.data.Info.tel,	//	收货人电话
					  receivaddress: res.data.Info.provinces + res.data.Info.city + res.data.Info.area + res.data.Info.detailadrs	//	收货详细地址
				  })
			  }else{
          that.setData({
					  savePostAddressButton: true,
					  savePostAddressMain: false,
            receivadrID: null,	//	收货地址ID
				  })
        }
		  }, 'POST')
	  }

	  //默认计算
    that.setData({
      aggregateamount: util.mul(parseInt(that.data.postNumber),parseFloat(that.data.unitprice)),  //累计金额
      totalamount: util.sub(util.mul(parseInt(that.data.postNumber),parseFloat(that.data.unitprice)),parseFloat(that.data.couponamount)),  //订单总金额
	  })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
	  return app.globalshare();
  },
  //洗衣件数
  numTap:function(e){
    var id = e.currentTarget.id;
    var num = this.data.postNumber;

    //干掉优惠券信息
    this.setData({
      couponid: null,	//优惠券id
      couponamount: 0,	//优惠金额
      couponstatus: false, //优惠券是否显示
    })

    if (id == '1') {
      if (num == 1) {
        this.setData({
          postNumber: num
        })
      } else {
        this.setData({
          postNumber: num - 1
        })
      }
    } else {
      this.setData({
        postNumber: num + 1
      })
    }
    //默认计算
    this.setData({
      aggregateamount: util.mul(parseInt(this.data.postNumber), parseFloat(this.data.unitprice)),  //累计金额
      totalamount: util.sub(util.mul(parseInt(this.data.postNumber), parseFloat(this.data.unitprice)), parseFloat(this.data.couponamount)),  //订单总金额
    })
      
  },
  // 确认提交
  savePostSuccessTap:function(){
	 var that = this
   var ystimes = util.functionrd(10, 1500);
   //是否有收货地址
   if (that.data.receivadrID){
     that.setData({
       submitst: true, //提交状态
     })
   }else{
     that.setData({
       submitst: false, //提交状态
     })
     wx.showModal({
       title: '提示',
       showCancel: false,
       content: '请选择收货地址'
     })
   }

   if (that.data.submitst && that.data.submitcs === 0){
     //开启加载
     wx.showLoading({
       title: '加载中',
       mask:true,
     })

     that.setData({
       submitst: false, //提交状态
     })
     
      var dats = {
        userinfoid: app.globalData.userInfoId, //用户ID
        ordertotalnum: that.data.postNumber,	//订单总件数
        amountpayable: that.data.aggregateamount,	//应付金额
        amountrealpay: that.data.totalamount,	//实付金额
        cabinetid: that.data.cabinetID, //智能柜ID
        cabinetdoorid: that.data.cabinetDoorID, //智能柜门ID
        addressid: that.data.receivadrID, //配送地址ID
        discountid: that.data.couponid, //优惠券ID
        ramark: that.data.remarks, //订单备注
      }

      //延时请求
      setTimeout(function () {
          //判断用户是否有默认收货地址
          util.AJAX('Home/Index/saveorderdata', dats, function (res) { //方法体
            //关闭加载
            wx.hideLoading()
            that.setData({ submitcs: 1 })
            if (res.data.StatusCode == 100) {  //下单成功
              var Info = res.data.Info
              wx.showToast({
                title: '订单创建成功',
                icon: 'success',
                duration: 2000,
                success: function (res) {
                  setTimeout(function () {
                    wx.redirectTo({
                      url: '/pages/pay/pay?ordernum=' + Info
                    })
                  }, 2000)
                }
              })
            } else {
              that.setData({
                submitcs: 0,
                submitst: true, //提交状态
              })
              wx.showModal({
                title: '提示',
                showCancel: false,
                content: res.data.Msg
              })
            }
          }, 'POST')
      }, ystimes)
    }
  },
  //收货地址操作
  addAddressButtonlist:function(){
    if (app.checkLogin()) {
      app.publicnavigateTologing('/pages/address_list/address_list?tps=ap')
    } else {
      app.navigateTologing() //跳转到登录
    }
  },
  //收货地址添加操作
  addAddressButton: function () {
    if (app.checkLogin()) {
      app.publicnavigateTologing('/pages/address/address?tps=bp')
    } else {
      app.navigateTologing() //跳转到登录
    }
  },
	//选择优惠券
	selectcoupon : function () {
    if (app.checkLogin()) {
      app.publicnavigateTologing('/pages/SavePost/selectCoupon/selectCoupon?totalmoney=' + this.data.aggregateamount)
    } else {
      app.navigateTologing() //跳转到登录
    }
	}
})